package com.qcdp.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.qcdp.dto.UserDTO;
import com.qcdp.utils.RedisConstants;
import com.qcdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
//拦截所有的请求只为刷新token，其余都放行
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //1.获取token
            String token = request.getHeader("authorization");
            if(StrUtil.isBlank(token)){
                //直接放行
                return true;
            }
            //2.获取reids中登录用户
            Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
            //3.判断当前redis中是否有登录用户
            if(map == null || map.isEmpty()){
                //4.没有登录我们也不拦截
                return true;
            }
            //4把登录用户的信息放到线程局部变量当中
            UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);

            UserHolder.saveUser(userDTO);
            //5.刷新token的有效时间
            stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

            //6.放行
            return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            UserHolder.removeUser();
    }
}
